package cn.zsssgjcx.hjsg.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.navigation.NavArgument;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.Navigation;
import androidx.navigation.fragment.NavHostFragment;
import androidx.navigation.ui.AppBarConfiguration;
import androidx.navigation.ui.NavigationUI;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.MapsInitializer;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.geocoder.GeocodeResult;
import com.amap.api.services.geocoder.GeocodeSearch;
import com.amap.api.services.geocoder.RegeocodeAddress;
import com.amap.api.services.geocoder.RegeocodeQuery;
import com.amap.api.services.geocoder.RegeocodeResult;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.material.bottomnavigation.BottomNavigationView;

import cn.zsssgjcx.hjsg.R;
import cn.zsssgjcx.hjsg.fragment.HomeFragment;
import cn.zsssgjcx.hjsg.utils.AMapUtils;
import cn.zsssgjcx.hjsg.utils.StatusBarUtils;
import cn.zsssgjcx.hjsg.utils.ToastUtils;

public class MainActivity extends AppCompatActivity implements GeocodeSearch.OnGeocodeSearchListener, View.OnClickListener, AMap.OnMarkerClickListener {

    private FusedLocationProviderClient fusedLocationClient;

    private GeocodeSearch geocoderSearch;
    private String addressName;
    private AMap aMap;
    private LatLonPoint latLonPoint = new LatLonPoint(39.90865, 116.39751);
    private String cityName;
    private String cityCode;

    private NavController controller;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.my_menu, menu);
        // 使应用程序图标向上导航
        ActionBar actionBar = getSupportActionBar();
        actionBar.hide(); //移除所有actionbar
        return true;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(ContextCompat.getColor(this, R.color.white));

            //状态栏设置为白亮，就是图标为白色
            StatusBarUtils.setLightStatusBar(this, true, false);
        }

        BottomNavigationView bottomNavigationView = findViewById(R.id.bottomNavigationView);
        controller = Navigation.findNavController(this,R.id.fragment);
        AppBarConfiguration configuration = new AppBarConfiguration.Builder(bottomNavigationView.getMenu()).build();
        NavigationUI.setupActionBarWithNavController(this,controller,configuration);
        NavigationUI.setupWithNavController(bottomNavigationView,controller);


//        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
//        getLastLocation();
//        ToastUtils.init(getApplicationContext());
//        privacyCompliance();
//        try {
//            geocoderSearch = new GeocodeSearch(this);
//            geocoderSearch.setOnGeocodeSearchListener(this);
//        } catch (AMapException e) {
//            throw new RuntimeException(e);
//        }

    }



    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //getLastLocation();
            }
        }
    }

    /**
     * 地理编码查询回调
     */
    @Override
    public void onGeocodeSearched(GeocodeResult result, int rCode) {
    }

    /**
     * 逆地理编码回调
     */
    @Override
    public void onRegeocodeSearched(RegeocodeResult result, int rCode) {
        //dismissDialog();
        Log.i("Test","---rCode="+rCode);
        if (rCode == AMapException.CODE_AMAP_SUCCESS) {
            if (result != null && result.getRegeocodeAddress() != null
                    && result.getRegeocodeAddress().getFormatAddress() != null) {
                addressName = result.getRegeocodeAddress().getFormatAddress()
                        + "附近";
                aMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
                        AMapUtils.convertToLatLng(latLonPoint), 15));

                //regeoMarker.setPosition(AMapUtils.convertToLatLng(latLonPoint));

                //ToastUtils.show(addressName);
                Log.i("Test","---addressName="+addressName);

                cityCode = result.getRegeocodeAddress().getCityCode();
                cityName = result.getRegeocodeAddress().getCity();


            } else {
                //ToastUtils.show(R.string.no_result);
                Log.i("Test","对不起，没有搜索到相关数据！");
            }
        } else {
            //ToastUtils.show(rCode);
            Log.i("Test","rCode=="+rCode);
        }
    }

    @Override
    public void onClick(View v) {

    }



    @Override
    public boolean onMarkerClick(Marker marker) {
        return false;
    }


    private void privacyCompliance() {
        MapsInitializer.updatePrivacyShow(MainActivity.this,true,true);
        SpannableStringBuilder spannable = new SpannableStringBuilder("\"亲，感谢您对XXX一直以来的信任！我们依据最新的监管要求更新了XXX《隐私权政策》，特向您说明如下\n1.为向您提供交易相关基本功能，我们会收集、使用必要的信息；\n2.基于您的明示授权，我们可能会获取您的位置（为您提供附近的商品、店铺及优惠资讯等）等信息，您有权拒绝或取消授权；\n3.我们会采取业界先进的安全措施保护您的信息安全；\n4.未经您同意，我们不会从第三方处获取、共享或向提供您的信息；\n");
        spannable.setSpan(new ForegroundColorSpan(Color.BLUE), 35, 42, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        new AlertDialog.Builder(this)
                .setTitle("温馨提示(隐私合规示例)")
                .setMessage(spannable)
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        MapsInitializer.updatePrivacyAgree(MainActivity.this,true);
                        //getLastLocation();
                    }
                })
                .setNegativeButton("不同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        MapsInitializer.updatePrivacyAgree(MainActivity.this,false);
                    }
                })
                .show();
    }

//    private void getLocation(){
//        // 创建AMapLocationClient实例
//        AMapLocationClient mLocationClient = null;
//        try {
//            mLocationClient = new AMapLocationClient(getApplicationContext());
//        } catch (Exception e) {
//            throw new RuntimeException(e);
//        }
//        // 初始化AMapLocationClientOption对象
//        AMapLocationClientOption mLocationOption = new AMapLocationClientOption();
//        // 设置定位模式为高精度模式
//        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
//        // 设置定位间隔，单位毫秒，默认为2000ms，最低1000ms
//        mLocationOption.setInterval(2000);
//        // 设置定位监听
//        mLocationClient.setLocationListener(mLocationListener);
//        // 绑定AMapLocationClientOption对象
//        mLocationClient.setLocationOption(mLocationOption);
//        // 启动定位
//        mLocationClient.startLocation();
//    }

//    private void getLastLocation() {
//        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
//                != PackageManager.PERMISSION_GRANTED) {
//            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
//        } else {
////            Task<Location> task = fusedLocationClient.getLastLocation();
////            task.addOnSuccessListener(new OnSuccessListener<Location>() {
////                @Override
////                public void onSuccess(Location location) {
////                    if (location != null) {
////                        // 使用位置数据
////                        double latitude = location.getLatitude();
////                        double longitude = location.getLongitude();
////                        // ...
////                        Log.d("Test","----latitude="+latitude);
////                        Log.d("Test","----longitude="+longitude);
////                    }
////                }
////            });
//
//
//
////            try{
////                GeocodeSearch geocoderSearch = new GeocodeSearch(this);
////                geocoderSearch.setOnGeocodeSearchListener((GeocodeSearch.OnGeocodeSearchListener) this);
////
////                // 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
////                RegeocodeQuery query = new RegeocodeQuery(new LatLonPoint(1,1), 200,GeocodeSearch.AMAP);
////
////                geocoderSearch.getFromLocationAsyn(query);
////
////            }catch (AMapException ex){
////
////            }
//
//            getLocation();
//
//        }
//    }

//    private void setCity(){
//        Bundle bundle =new Bundle();
//        bundle.putString("cityCode", cityCode);
//        bundle.putString("cityName", cityName);
//        //获取Navigation的NavGraph
//        NavGraph graph = controller.getGraph();
//        //set值
//        NavArgument.Builder builder = new NavArgument.Builder();
//        builder.setDefaultValue(bundle);
//        builder.build();
//        //放到NavGraph中
//        graph.addArgument("type", builder.build());
//
//
//    }

//    public void getAddress(final LatLonPoint latLonPoint) {
//        //showDialog();
//        RegeocodeQuery query = new RegeocodeQuery(latLonPoint, 200,
//                GeocodeSearch.AMAP);// 第一个参数表示一个Latlng，第二参数表示范围多少米，第三个参数表示是火系坐标系还是GPS原生坐标系
//
//        geocoderSearch.getFromLocationAsyn(query);// 设置异步逆地理编码请求
//
//
//    }

    // 创建定位监听
//    AMapLocationListener mLocationListener = new AMapLocationListener() {
//        @Override
//        public void onLocationChanged(AMapLocation aMapLocation) {
//            if (aMapLocation != null) {
//                if (aMapLocation.getErrorCode() == 0) {
//                    // 获取当前定位结果
//                    double latitude = aMapLocation.getLatitude(); // 纬度
//                    double longitude = aMapLocation.getLongitude(); // 经度
//                    String address = aMapLocation.getAddress(); // 地址信息
//                    // 可以在这里对获取的位置信息进行处理
//                    Log.i("Test","----latitude="+latitude);
//                    Log.i("Test","----longitude="+longitude);
//                    Log.i("Test","----address="+address);
//
//                    LatLonPoint latLonPoint = new LatLonPoint(latitude,longitude);
//                    getAddress(latLonPoint);
//                } else {
//                    // 定位失败，显示错误信息
//                    Log.e("AmapError", "location Error, ErrCode:" + aMapLocation.getErrorCode() + ", errInfo:" + aMapLocation.getErrorInfo());
//                }
//            }
//        }
//
//    };
}